#!/bin/bash

set -e

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

#下载依赖和工具包
function install_development() {
  sudo yum install -y wget tar unzip patch 
  source /etc/profile
}

#获取libgtextutils
function download_libgtextutils() {
  echo "# libgtextutils正在下载"
  cp  "$2"/src/libgtextutils-0.7.tar.gz  "$1" 
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# libgtextutils下载成功\033[0m"
  else
    echo -e "\033[31m# libgtextutils下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_libgtextutils() {
  echo "# libgtextutils正在安装"
  tar -xzf "$1"/libgtextutils-0.7.tar.gz -C "$1" && rm -rf "$1"/libgtextutils-0.7.tar.gz
  cp "$3"/libgtextutils.patch "$1"/libgtextutils-0.7
  cd "$1"/libgtextutils-0.7
  patch -p1 <./libgtextutils.patch
  ./reconf
  CC=clang CXX=clang++ ./configure --prefix="$2"/libgtextutils-0.7 --build=aarch64-unknown-linux-gnu  --enable-static=yes  --enable-shared
  make -j$(nproc) && make -j$(nproc) install
  echo -e "\033[1;32;1m# libgtextutils已经安装完毕\033[0m"
}

function write_libgtextutils_module() {
  cat >"$1/libgtextutils-0.7/libgtextutils_modulefiles" <<EOF
#%Module1.0
conflict libgtextutils
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
  variable modfile
  set modfile_path [file dirname \$modfile]
  return \$modfile_path
}
set pwd [getModulefileDir]
set LIBGTEXTUTILS \$pwd
setenv LIBGTEXTUTILS \$LIBGTEXTUTILS
prepend-path LD_LIBRARY_PATH \$LIBGTEXTUTILS/lib
EOF
}

function main() {
    is_check_build_install_directory "$1" "$2" "libgtextutils-0.7.sh"
    is_equal_build_install_path "$1" "$2"
    install_development
    download_libgtextutils "$1" "$4"
    install_libgtextutils "$1" "$2" "$3"
    write_libgtextutils_module "$2"
    rm -rf "$1"/libgtextutils-0.7
}

main "$@"